<template>
  <div class="headerbox">
    <van-nav-bar title="订单结算" left-text="" left-arrow @click-left="onClickLeft">
      <!-- <template #right>
        <van-icon name="search" size="18" />
      </template> -->
    </van-nav-bar>
  </div>
  <div class="clear"></div>
  <div class="h50" style="height: 10px;"></div>
  <div class="clear"></div>
  <router-link to="/address">
    <div class="addressbox">
      <p style="margin-top: 5px;">{{ address }} {{ uname }}</p>
      <img src="/images/go.png">
    </div>
  </router-link>

  <div class="clear"></div>
  <div class="allkbox"></div>
  <div class="clear"></div>
  <div class="buybox">
    <div class="itembox" v-if="isStatic == 1" v-for="item in prdList">
      <div class="dp" style="border-top: 1px solid #eeeeee;">
        <p style="margin-top: 5px;">前途家床品旗舰店</p><img src="/images/go.png">
      </div>
      <div class="dpnr">
        <div class="L"><img :src="item.shopUrl_text"></div>
        <div class="R">
          <div class="tit">{{ item.content }}</div>
          <div class="sub">尺寸：200*240cm</div>
          <div class="price" v-if="isStatic == 1">
            <p>￥{{ item.price }}</p><span>×1</span>
          </div>
          <div class="price" v-else="isStatic==2">
            <p>￥{{ item.price * item.num }}</p><span>×{{ item.num }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="itembox" v-if="isStatic == 2" v-for="item in settlementList">
      <div class="dp" style="border-top: 1px solid #eeeeee;">
        <p style="margin-top: 5px;">前途家床品旗舰店</p><img src="/images/go.png">
      </div>
      <div class="dpnr">
        <div class="L"><img :src="item.product.shopUrl_text"></div>
        <div class="R">
          <div class="tit">{{ item.product.content }}</div>
          <div class="sub">尺寸：200*240cm</div>
          <div class="price" v-if="isStatic == 1">
            <p>￥{{ item.price }}</p><span>×1</span>
          </div>
          <div class="price" v-else="isStatic==2">
            <p>￥{{ item.product.price * item.num }}</p><span>×{{ item.num }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="clear"></div>
    <div class="allkbox"></div>
    <div class="clear"></div>
    <!-- <div class="itemboxcon">
      <p>支付方式</p>
      <img src="/images/go.png">
    </div> -->
    <!-- 优惠券单元格 -->
    <van-coupon-cell :coupons="coupons" :chosen-coupon="chosenCoupon" @click="showList = true" />
    <!-- 优惠券列表 -->
    <van-popup v-model:show="showList" round position="bottom" style="height: 90%; padding-top: 4px;">
      <van-coupon-list :coupons="coupons" :chosen-coupon="chosenCoupon" :disabled-coupons="disabledCoupons"
        @change="onChange" @exchange="onExchange" />
    </van-popup>

    <!-- <div class="allkbox"></div> -->
    <!-- <div class="itemboxcon" v-if="totalPrice < doorsill">
      <p style="margin-top: 5px;">运费</p>
      <img src="/images/go.png">
      <span>{{ freight }}元</span>
    </div> -->
    <!-- <div class="itemboxcon" v-else>
      <p style="margin-top: 5px;">运费</p>
      <img src="/images/go.png">
      <span></span>
    </div> -->
    <div class="allkbox"></div>
    <van-cell v-if="totalPrice < doorsill" title="运费" is-link :value="`${freight}元`" />
    <van-cell v-else title="运费" is-link :value="`已满${doorsill}元，已包邮`" />
    <div class="allkbox"></div>
    <van-cell-group inset>
      <van-field v-model="value" label="请填写备注" placeholder="买家留言" clearable />
    </van-cell-group>
    <!-- <van-cell-group inset>
      <van-field label="请填写备注" placeholder="买家留言" label-align="left" />
    </van-cell-group> -->

    <!-- <van-cell-group inset>
      <van-field v-model="value" clearable label="请填写备注" placeholder="买家留言" />
    </van-cell-group> -->
    <!-- <div class="itemboxcon">
      <p style="margin-top: 7px;">买家留言</p>
      <font>请填写备注（选填）</font>
      <img src="/images/go.png">
    </div> -->
  </div>
  <div class="clear"></div>
  <div class="h54"></div>
  <div class="clear"></div>
  <div class="footerBox">
    <div class="footer3" style="z-index: 1;">
      <div class="L">
        <p style="margin-top: 15px;">总计：<span>{{ totalPrice }}</span></p>
      </div>
      <div class="R">
        <div @click="confirmBuy">确认支付</div>
      </div>
    </div>
  </div>
</template>

<style scoped></style>

<script setup>
import { ref, onMounted } from "vue";
import { showToast } from 'vant';
import { useRoute } from "vue-router";
import { POST } from "../services/request";
import { showConfirmDialog } from 'vant';
const route = useRoute()

const remark = ref('');

const value = ref('');
// console.log(totalprice,111);

const pids = ref([]);

const cartNum = ref(1);


const userData = JSON.parse(localStorage.getItem('LoginUser'));
const addressData = JSON.parse(localStorage.getItem('currAddress'))
const address = ref(null)
const uname = ref(null)

const freight = ref(0)
const doorsill = ref(0)

// 过期的将type=-1,这里是存需要更新的id的值
const updataTypeId = ref([])
// 原价
const originPrice = ref(null)


// 当前时间搓
const timestamp = ref(Math.floor(Date.now() / 1000));

// 从路由获取的id
const cartIds = ref(JSON.stringify(route.query.ids));
// console.log(cartIds,'0000000000000000');

const price = ref(route.query.price);
// 判断是从购物车跳过来，还是点击立即购买跳过来: 1为立即购买 2为购物车结算
const isStatic = ref(null)
isStatic.value = route.query.isStatic;
// console.log(isStatic.value);

const totalPrice = ref(0);
totalPrice.value = JSON.parse(price.value)

const singleNum = ref([]);

const prdList = ref([]);


const settlementList = ref([])

onMounted(async () => {
  await getSettlementCart();
  await getUserCoupon();
})
// 购物车立即购买
// 获取提交订单的列表
const getSettlementCart = async () => {
  // console.log(cartIds.value);
  const settlementCartRes = await POST({
    url: '/Settlement/getSettleList',
    params: {
      uid: userData.id,
      mobile: userData.mobile,
      ids: cartIds.value,
      price: totalPrice.value,
      isStatic: isStatic.value,
    }
  })
  if (settlementCartRes.code === 1) {
    // console.log(settlementCartRes.data, '99999999999999999999');
    settlementList.value = settlementCartRes.data.settleList
    settlementList.value.forEach(item => {
      singleNum.value.push(item.num)
    })
    // console.log(singleNum.value);

    prdList.value = settlementCartRes.data.prdList
    // console.log(settlementList.value,'settlementList.value');
    totalPrice.value = settlementCartRes.data.totalPrice
    // 66666666666
    // console.log(totalPrice.value,'totalPrice.value');
    if (isStatic.value == 2) {
      settlementCartRes.data.settleList.forEach(item => {
        pids.value.push(item.pid);
      })
    }
    if (isStatic.value == 1) {
      prdList.value.forEach(item => {
        // console.log(item.id,'jasjlasjas');
        pids.value.push(item.id);
      })
    }

    // console.log(JSON.stringify(pids.value),'pids.value');
    pids.value = JSON.stringify(pids.value);
    // 转换为数值类型并保留两位小数
    // totalPrice.value = priceStr.toFixed(2);
    address.value = addressData.address
    // console.log(addressData.id, 'id66');

    uname.value = addressData.name

    // console.log(typeof totalPrice.value);
    // resPrice.value = int(totalPrice.value / 100);
  }
}

const onClickLeft = () => {
  // getSettlementCart()
  history.back()
};

// const onClickRight = () => showToast('按钮');

// const coupon = {
//   available: 1,
//   condition: '无门槛\n最多优惠12元',
//   reason: '',
//   value: 150,
//   name: '优惠券名称',
//   startAt: 1489104000,
//   endAt: 1514592000,
//   valueDesc: '1.5',
//   unitDesc: '元',
// };

// 可用优惠卷列表
const coupons = ref([]);
// 不可用优惠卷列表
const disabledCoupons = ref([])
const showList = ref(false);
const chosenCoupon = ref(-1);
// 用于传给确认支付的时候
const selectCoupon = ref(null)
const onChange = (index) => {
  console.log(index, 'originPrice');
  totalPrice.value = originPrice.value
  showList.value = false;
  chosenCoupon.value = index;
  // 拿到选中的优惠卷后
  if (chosenCoupon.value !== -1) {
    // console.log(coupons.value[index]);
    const isSelectCoupon = coupons.value[index]
    
    // console.log(isSelectCoupon.id,'9999999');

    selectCoupon.value = isSelectCoupon.id
    // console.log(selectCoupon.value,'1111');
    // console.log(chosenCoupon.value);
    if (isSelectCoupon) {
      // isSelectCoupon.rstatus：1为折扣 2为满减
      if (isSelectCoupon.rstatus == 1) {
        // console.log(isSelectCoupon.rstatus);
        totalPrice.value *= isSelectCoupon.discount;
        // totalPrice.value.toFixed(2)
      } else {
        totalPrice.value -= isSelectCoupon.discount;
        // totalPrice.value.toFixed(2)
      }
    }
  }
  // console.log(isSelectCoupon,'pkkjsjioiisoi');
  // 不满100就加运费
  if (totalPrice.value < doorsill.value) {
    // console.log(1111);
    totalPrice.value += Number(freight.value)
  }
  totalPrice.value = totalPrice.value.toFixed(2)
};

// 兑换码
const onExchange = (code) => {
  // console.log(code);
  coupons.value.push(coupon);
};

// 查询用户领取的优惠券
const getUserCoupon = async () => {
  const getUserCRes = await POST({
    url: '/Coupon/getUserReceive',
    params: {
      uid: userData.id,
      mobile: userData.mobile,
    }
  })
  if (getUserCRes.code === 1) {
    // console.log(getUserCRes.data);
    const receiveList = getUserCRes.data.receiveCouponRes
    // console.log(receiveList.coupon.endAt);

    // 获取运费
    freight.value = Number(getUserCRes.data.freight).toFixed(2)
    // 获取运费门槛
    doorsill.value = Number(getUserCRes.data.doorsill)
    // console.log('freight.value:',freight.value,'doorsill.value:',doorsill.value);
    // console.log(receiveList,'receiveList');
    receiveList.forEach(element => {
      // console.log(element.coupon.condition_price);
      // type : 1-已使用, 0-未使用, -1-已失效
      // 如果当前时间大于结束时间，则把type变为-1
      if (timestamp.value > element.coupon.endAt) {
        // 存要更新的id的值
        updataTypeId.value.push(element.id)
      }
    });
    // console.log(updataTypeId.value);
    // 更新过期状态的方法
    updateCType(JSON.stringify(updataTypeId.value));
    // 获取可用或不可的列表，过期的则不显示
    receiveList.forEach(element => {
      // console.log(element.coupon.condition_price);
      // type : 1-已使用, 0-未使用, -1-已失效
      // 如果满足条件，且是未使用状态，的就将其追加到可用的列表
      if (totalPrice.value >= element.coupon.condition_price && element.type == 0) {
        coupons.value.push(element.coupon);
      }
      // 如果不满足门槛，且是未使用状态（0），则追加到不可使用列表
      if (totalPrice.value < element.coupon.condition_price && element.type == 0) {
        disabledCoupons.value.push(element.coupon);
      }
      // else {
      //   disabledCoupons.value.push(element.coupon);
      // }
    });
    // 原价
    originPrice.value = totalPrice.value

    // 如果选中是选中哪张券的状态时，先抵扣券，后面再判断是否加运费
    if (chosenCoupon.value !== -1) {
      onChange();
    } else {
      // 不满100就加运费
      if (totalPrice.value < doorsill.value) {
        totalPrice.value += Number(freight.value)
      }
    }
    // console.log(totalPrice.value,'totalPrice.value');
    // console.log(chosenCoupon.value,'totalPrice.value');

  }
}

// 领取的优惠券的type : 1-已使用, 0-未使用, -1-已失效
// 将过期的type置为-1
const updateCType = async (ids) => {
  // console.log(ids,'88888888');
  const updateTypyeRes = await POST({
    url: '/Settlement/updateType',
    params: {
      ids,
      uid: userData.id,
      mobile: userData.mobile,
    }
  })
}


// 确认支付
const confirmBuy = () => {
  // 获取评论
  remark.value = value.value


  showConfirmDialog({
    title: '支付',
    message:
      '是否支付本次订单',
  })
    .then(async () => {
      // on confirm
      // console.log(selectCoupon.value,'1111');
      
      const confirmRes = await POST({
        url: '/Settlement/confirmBuy',
        params: {
          uid: userData.id,
          couponId: selectCoupon.value,
          mobile: userData.mobile,
          totalPrice: totalPrice.value,
          pids: pids.value,
          businessaddrid: addressData.id,
          createtime: timestamp.value,
          remark: remark.value,
          isStatic: isStatic.value,
          status: 1
        }
      })
      if (confirmRes.code === 1) {
        showToast(confirmRes.msg);
        history.back();
      } else {
        showToast(confirmRes.msg);
      }
    })
    // 取消操作,取消时现正常生成订单
    .catch(async () => {
      const confirmRes = await POST({
        url: '/Settlement/confirmBuy',
        params: {
          uid: userData.id,
          couponId: selectCoupon.value,
          mobile: userData.mobile,
          totalPrice: totalPrice.value,
          pids: pids.value,
          businessaddrid: addressData.id,
          createtime: timestamp.value,
          remark: remark.value,
          isStatic: isStatic.value,
          status: -2
        }
      })
      if (confirmRes.code === 1) {
        // showToast('已取消支付，可到订单进行支付');
        showToast(confirmRes.msg);
        history.back();
      } else {
        showToast(confirmRes.msg);
      }
    });

  // console.log(selectCoupon.value);
  // console.log('确认支付');
  // console.log(totalPrice.value);
}



</script>